package com.infolab.aims.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.infolab.aims.GlobalConstant;
import com.infolab.aims.common.AbstractController;
import com.infolab.aims.common.CommonUtil;
import com.infolab.aims.common.InQueryHelper;
import com.infolab.aims.common.ParameterDateQueryHelper;
import com.infolab.aims.common.bean.SearchCriteria;
import com.infolab.aims.common.bean.SearchResult;
import com.infolab.aims.common.exception.DataStoreException;
import com.infolab.aims.domain.Department;
import com.infolab.aims.domain.Location;
import com.infolab.aims.domain.Vendor;
import com.infolab.aims.domain.asset.AssetEquipmentPK;
import com.infolab.aims.domain.asset.AssetModel;
import com.infolab.aims.domain.purchase.PurchaseOrder;
import com.infolab.aims.domain.purchase.PurchaseOrderDetail;
import com.infolab.aims.domain.purchase.PurchaseOrderRepair;
import com.infolab.aims.domain.receive.DeliveryOrder;
import com.infolab.aims.domain.receive.DeliveryOrderComponent;
import com.infolab.aims.domain.receive.DeliveryOrderEquipment;
import com.infolab.aims.service.intf.AssetModelService;
import com.infolab.aims.service.intf.AssetTransactionFacadeService;
import com.infolab.aims.service.intf.DeliveryOrderService;
import com.infolab.aims.service.intf.PurchaseOrderService;


@Controller
@RequestMapping("/deliveryOrder")
@SessionAttributes(value=DeliveryOrderController.SESSION_SEARCH_CRITERIA)
public class DeliveryOrderController extends AbstractController {
	
	public static final String SESSION_SEARCH_CRITERIA ="searchCriteria";
	public static final String CONTEXT_PATH ="/deliveryOrder";
	public static final String JSP_MAIN_FORM_COMPONENT="deliveryOrderFormComp";
	public static final String JSP_MAIN_FORM_EQUIPMENT="deliveryOrderFormEquip";
	public static final String JSP_MAIN_FORM_EQUIPMENT_REPAIR="deliveryOrderFormEquipForRepair";
	
	public static final String JSP_MAIN_SEARCH="deliveryOrderSearch";

	@Autowired
	DeliveryOrderService deliveryOrderService;
	
	@Autowired
	PurchaseOrderService purchaseOrderService;

	@Autowired
	AssetModelService assetModelService;
	@Autowired
	AssetTransactionFacadeService assetTransactionFacadeService;
	
	Log logger = LogFactory.getLog(getClass());
	
	@ModelAttribute(DeliveryOrderController.SESSION_SEARCH_CRITERIA)
	public SearchCriteria getDeliveryOrderSearchCriteria()
	{
		return new SearchCriteria();
	}
	

	@RequestMapping(value="search")
	public String searchDeliveryOrder(@ModelAttribute(DeliveryOrderController.SESSION_SEARCH_CRITERIA) SearchCriteria searchCriteria,@ModelAttribute("currentSearchCriteria") SearchCriteria currentSearchCriteria,Model model,HttpServletRequest request) {
		
		Date dateFrom = null;
		Date dateTo = null;
		
		try{
			if(!checkNullEmpty(searchCriteria.getSearchCriteria("dateFrom"))) {			 
				dateFrom = new SimpleDateFormat(GlobalConstant.DATE_FORMAT_JAVA).parse(searchCriteria.getSearchCriteria("dateFrom").toString());
			}
			
			if(!checkNullEmpty(searchCriteria.getSearchCriteria("dateTo"))) {			  
				dateTo= new SimpleDateFormat(GlobalConstant.DATE_FORMAT_JAVA).parse(searchCriteria.getSearchCriteria("dateTo").toString());
			}
		}
		catch (ParseException e) {
			logger.error(CommonUtil.getStackTrace(e));
		}
		
		
		if(currentSearchCriteria.getCurPage()!=null)
			searchCriteria.setCurPage(currentSearchCriteria.getCurPage());
		
		if(!checkNullEmpty(dateFrom) &&  
				!checkNullEmpty(dateTo)) {
		
			searchCriteria.addSearchCriteria("deliveryOrderDate", new ParameterDateQueryHelper("dateCreated",dateFrom, dateTo));
		}
		
		else if(!checkNullEmpty(dateFrom) &&  
				checkNullEmpty(dateTo)){
			searchCriteria.addSearchCriteria("deliveryOrderDate", new ParameterDateQueryHelper("dateCreated",dateFrom, null));
		}		
			
		else if(checkNullEmpty(dateFrom) &&  
				!checkNullEmpty(dateTo)){
			searchCriteria.addSearchCriteria("deliveryOrderDate", new ParameterDateQueryHelper("dateCreated",null, dateTo));
		}
		
		else
		{
			searchCriteria.addSearchCriteria("deliveryOrderDate", new ParameterDateQueryHelper("dateCreated",null, null));
		}
		
		Department accessDepartment = getCurrentDepartment(request);
		if(accessDepartment !=null)
			searchCriteria.addSearchCriteria("accessDepartmentId", accessDepartment.getDepartmentId());
				
		SearchResult searchResult = deliveryOrderService.searchDeliveryOrder(searchCriteria);
		model.addAttribute(searchResult);
		
		return JSP_MAIN_SEARCH;
	}
	
	
	@RequestMapping(value="create", method = RequestMethod.GET)
	public String createDeliveryOrder(Model model,HttpServletRequest request) {
		populateModel(model,request);
		model.addAttribute(new DeliveryOrder());
		return JSP_MAIN_FORM_COMPONENT;
		
	}
	
	
	@RequestMapping(value="creates", method = RequestMethod.GET)
	public String createDeliveryOrderForEquipment(Model model,HttpServletRequest request) {
		populateModel(model,request);
		model.addAttribute(new DeliveryOrder());
		return JSP_MAIN_FORM_EQUIPMENT;		
		// NEED TO RETURN CURRENT VIEW
	}
	
	@RequestMapping(value="creates", method = RequestMethod.POST)
	public String createDeliveryOrder(@ModelAttribute DeliveryOrder deliveryOrder, BindingResult result,Model model,HttpServletRequest request) {
		
		
		PurchaseOrder purchaseOrder = purchaseOrderService.getPurchaseOrder(deliveryOrder.getPurchaseOrder().getPurchaseOrderId());
		deliveryOrder.setPurchaseOrder(purchaseOrder);
		// get purchase order no. again do the same process. getting details from the DB corresponding to the PO order from select
		//String poAssetType = deliveryOrder.getPurchaseOrder().getAssetType()!=null? (String)deliveryOrder.getPurchaseOrder().getAssetType():"";
		// PO asset type = component or equipment
		String poAssetType = purchaseOrder.getAssetType()!=null? (String)purchaseOrder.getAssetType():"";		
		String poOrderType = purchaseOrder.getPurchaseOrderType()!=null? (String)purchaseOrder.getPurchaseOrderType():"" ;
		
		if(poAssetType.equals(AssetModel.ASSETTYPE_EQUIPMENT) ){
			populateModel(model,request);
			
			if(poOrderType.equalsIgnoreCase(PurchaseOrder.PURCHASEORDERTYPE_NEW))
				return JSP_MAIN_FORM_EQUIPMENT;
				
			else
				return JSP_MAIN_FORM_EQUIPMENT_REPAIR;
			
		}
		else{
			populateModel(model,request);
			return JSP_MAIN_FORM_COMPONENT;
		}
	
	}
	
		
	@RequestMapping(value="create",method=RequestMethod.POST)
	public String saveDeliveryOrder(@ModelAttribute DeliveryOrder deliveryOrder, BindingResult result,Model model,HttpServletRequest request) {
		
		// based on asset type of deliveryOrder.purchaseOrder.assettype
		String target = null;
		PurchaseOrder purchaseOrder = purchaseOrderService.getPurchaseOrder(deliveryOrder.getPurchaseOrder().getPurchaseOrderId());
		
		deliveryOrder.setPurchaseOrder(purchaseOrder);
		
		if(deliveryOrder.getPurchaseOrder().isNewPurchaseOrder()){
			deliveryOrder.setLocation(purchaseOrder.getLocation());
		}
		else{
			Location loc = findLocation(request, deliveryOrder.getLocation().getLocationId());
			deliveryOrder.setLocation(loc);
		}
		String assetType = deliveryOrder.getPurchaseOrder().getAssetType()!=null? (String)deliveryOrder.getPurchaseOrder().getAssetType():"";
		String poOrderType = purchaseOrder.getPurchaseOrderType()!=null?(String)purchaseOrder.getPurchaseOrderType():"" ;
		
		

		if(assetType.equals(AssetModel.ASSETTYPE_EQUIPMENT)){
			
			if(poOrderType.equalsIgnoreCase(PurchaseOrder.PURCHASEORDERTYPE_NEW))
				target =JSP_MAIN_FORM_EQUIPMENT;
				
			else
				target =JSP_MAIN_FORM_EQUIPMENT_REPAIR;
			
		}
		else{
			target = JSP_MAIN_FORM_COMPONENT;
			if(deliveryOrder.getDeliveryOrderComponents()!=null && deliveryOrder.getDeliveryOrderComponents().size()>0)
			{
				int size = deliveryOrder.getDeliveryOrderComponents().size();
				int[] qtyReceiving = new int[size];
				for(int i=0;i<size;i++){
					qtyReceiving[i] = deliveryOrder.getDeliveryOrderComponents().get(i).getQuantityReceiving()!=null? 
							deliveryOrder.getDeliveryOrderComponents().get(i).getQuantityReceiving().intValue():-1;
							
				}
				model.addAttribute("qtyReceiving",qtyReceiving);
			}
		}
		populateModel(model,request);
		if(poOrderType.equalsIgnoreCase(PurchaseOrder.PURCHASEORDERTYPE_NEW)){
			deliveryOrder.setDeliveryOrderType(DeliveryOrder.DELIVERYORDERTYPE_NEW);
		}
		else{
			deliveryOrder.setDeliveryOrderType(DeliveryOrder.DELIVERYORDERTYPE_REPAIR);
		}
		
		if (validateDeliveryOrder(deliveryOrder, result)) {	
			return target;
		}
		deliveryOrder.setCreatedBy(getCurrentUserName(request));
		
		try
		{
			

			Department accessDepartment = deliveryOrder.getPurchaseOrder().getAccessDepartment();
			deliveryOrder.setAccessDepartment(accessDepartment);
			prepareAuditObject(deliveryOrder, request);
			assetTransactionFacadeService.createDeliveryOrder(deliveryOrder);
		}
		catch(DataStoreException e)
		{
			if(e.isUniqueConstraint())
			{
				if(StringUtils.equalsIgnoreCase("deliveryOrderCode", e.getColumnName()))
					result.rejectValue("deliveryOrderCode", "error.exist", new String[]{deliveryOrder.getDeliveryOrderCode()}, "");
				else
					result.reject("error.unknown", new String[]{e.getMessage()}, "");
			}
			else
				result.reject("error.unknown", new String[]{e.getMessage()}, "");
			
			return target;
		}
		setSuccessMessage(getMessageResources("success.create","deliveryOrder " + deliveryOrder.getDeliveryOrderCode()));
		
		return "redirect:"+CONTEXT_PATH+"/view/" + deliveryOrder.getDeliveryOrderId();	
	}
	
	
	@RequestMapping(value={"view/{id}","detail/{id}"}, method = RequestMethod.GET)
	public String detailPurchaseOrder(@PathVariable Integer id,Model model,HttpServletRequest request) {	
		
		DeliveryOrder deliveryOrder = deliveryOrderService.getDeliveryOrder(id);
		populateModel(model,request);
		model.addAttribute(deliveryOrder);
		String target = null;
		String assetType = deliveryOrder.getPurchaseOrder().getAssetType()!=null? (String)deliveryOrder.getPurchaseOrder().getAssetType():"";
		String poOrderType = deliveryOrder.getPurchaseOrder().getPurchaseOrderType()!=null? (String)deliveryOrder.getPurchaseOrder().getPurchaseOrderType():"" ;
		
		if(assetType.equals(AssetModel.ASSETTYPE_EQUIPMENT)){
			if(poOrderType.equalsIgnoreCase(PurchaseOrder.PURCHASEORDERTYPE_NEW))
				target =JSP_MAIN_FORM_EQUIPMENT;
				
			else
				target =JSP_MAIN_FORM_EQUIPMENT_REPAIR;
		}
		else{
			target = JSP_MAIN_FORM_COMPONENT;
		}
		return target;
	}
	
	@RequestMapping(value={"importFile/{id}"}, method = RequestMethod.POST)
	public @ResponseBody String importFile(@PathVariable Integer id,Model model,HttpServletRequest request,HttpServletResponse response) {

		

		List<DeliveryOrderEquipment> deliveryOrderEquipments = new ArrayList<DeliveryOrderEquipment>();
		Map map = new HashMap();
		
		try
		{
			 String filename = request.getHeader("X-File-Name");
			 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			 MultipartFile multipartFile = multipartRequest.getFile("excelFile");			   
			 InputStream    is = multipartFile.getInputStream();
			 Workbook workbook = null;
			 
			try
			{
				WorkbookSettings ws = new WorkbookSettings();
				ws.setInitialFileSize(1);
				workbook = Workbook.getWorkbook(is);
				Sheet sheet  = workbook.getSheet(0);
				PurchaseOrder purchaseOrder = purchaseOrderService.getPurchaseOrder(id);
				
				String receivedSerialNo="";
				String assetModelCode="";
				//String indexSNo="";
				PurchaseOrderDetail purchaseOrderDetail= new PurchaseOrderDetail();
				Map<Integer,Integer> purchaseMap = new HashMap<Integer, Integer>();
				Vector<String> equipmentsInImportedFile = new Vector<String>();
				Vector<AssetEquipmentPK> entireEquipments = new Vector<AssetEquipmentPK>();
				
				List<String> serialNos = new ArrayList<String>();
				for(int i=1;i<sheet.getRows();i++){					
					String serialNo = sheet.getCell(1, i).getContents()!=null? sheet.getCell(1, i).getContents().trim():"";				
					serialNos.add(serialNo);
				}
				
				
				InQueryHelper helper = new InQueryHelper("serialNo", serialNos);
				SearchCriteria criteria = new SearchCriteria();
				criteria.addSearchCriteria("serialNo", helper);
				List<String> list = assetModelService.searchSerialNoCriteria(criteria);

				
				for(int i=1;i<sheet.getRows();i++){
				
					 AssetModel assetModel = new AssetModel();
					 DeliveryOrderEquipment deliveryOrderEquipment = new DeliveryOrderEquipment();
					 assetModelCode = sheet.getCell(0, i).getContents()!=null?sheet.getCell(0, i).getContents().trim():"";
					 receivedSerialNo = sheet.getCell(1, i).getContents()!=null? sheet.getCell(1, i).getContents().trim():"";					
					 assetModel.setAssetModelCode(assetModelCode);
					 
					 purchaseOrderDetail = purchaseOrder.findPurchaseOrderDetails(assetModel);
					 /*SearchCriteria searchCriteria = new SearchCriteria();
					 searchCriteria.addSearchCriteria("serialNo", receivedSerialNo);
					 AssetEquipment assetEquipment = assetModelService.findAssetEquipment(searchCriteria);*/
					 
					if(purchaseOrderDetail==null){
						deliveryOrderEquipment.setDeleted(true);
						deliveryOrderEquipment.setAssetModel(assetModel);	
					}
					else
					{
						deliveryOrderEquipment.setAssetModel(purchaseOrderDetail.getAssetModel());
						assetModel.setAssetModelId(purchaseOrderDetail.getAssetModel().getAssetModelId());
						if(equipmentsInImportedFile.contains(receivedSerialNo))
						{
							deliveryOrderEquipment.setDeleted(true);
						}						
						/*else if(assetEquipment!=null){
							deliveryOrderEquipment.setDeleted(true);
						}*/

						else if(list.contains(receivedSerialNo)){
							deliveryOrderEquipment.setDeleted(true);
						}

						else
						{
							equipmentsInImportedFile.addElement(receivedSerialNo);
							int receievedQty =  purchaseOrderDetail.getQuantityReceived()!=null?purchaseOrderDetail.getQuantityReceived().intValue():0;
							int orderedQty =  purchaseOrderDetail.getQuantityOrder()!=null?purchaseOrderDetail.getQuantityOrder().intValue():0;
							if(null==purchaseMap.get(assetModel.getAssetModelId())){
								purchaseMap.put(assetModel.getAssetModelId(), receievedQty+1);
							}				
							
								int qty = purchaseMap.get(assetModel.getAssetModelId());
								//if(receievedQty>=qty)
								if(orderedQty<qty)
								{
									//reject
									deliveryOrderEquipment.setDeleted(true);
								}
								else
								{
									qty++;
									purchaseMap.put(assetModel.getAssetModelId(),qty);
									
								}
						}
						
						
					}
										
					deliveryOrderEquipment.setReceivedSerialNo(receivedSerialNo);
					deliveryOrderEquipments.add(deliveryOrderEquipment);
					
				}

				
			}
			
				catch(ArrayIndexOutOfBoundsException e){
						map.put("format","error");
						logger.error(CommonUtil.getStackTrace(e));
				}
				catch(Exception e){
					logger.error(CommonUtil.getStackTrace(e));
				}
				finally{
						if(workbook!=null){
							workbook.close();
						}
				}

		}
		catch(Exception e ){
			logger.error(CommonUtil.getStackTrace(e));
			}
		
			
			
			map.put("success", "true");
			map.put("result", deliveryOrderEquipments);
			
			StringWriter writer = new StringWriter();
	        ObjectMapper mapper = new ObjectMapper();
	        JsonGenerator jsonGenerator;
			try {
				jsonGenerator = mapper.getJsonFactory().createJsonGenerator(writer);
				mapper.writeValue(jsonGenerator, map);
				return writer.toString();
			} catch (IOException e) {
				logger.error(CommonUtil.getStackTrace(e));
			}
			
			return "[]";
		        
			
	}
	
	
	@RequestMapping(value={"importFileForRepair/{id}"}, method = RequestMethod.POST)
	public @ResponseBody String importFileForRepair(@PathVariable Integer id,Model model,HttpServletRequest request,HttpServletResponse response) {

		

		List<DeliveryOrderEquipment> deliveryOrderEquipments = new ArrayList<DeliveryOrderEquipment>();
		 Map map = new HashMap();
		try
		{
			 String filename = request.getHeader("X-File-Name");
			 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			 MultipartFile multipartFile = multipartRequest.getFile("excelFile");			   
			 InputStream    is = multipartFile.getInputStream();
			 Workbook workbook = null;
			
			 
			try
			{
				WorkbookSettings ws = new WorkbookSettings();
				ws.setInitialFileSize(1);
				workbook = Workbook.getWorkbook(is);
				Sheet sheet  = workbook.getSheet(0);
				PurchaseOrder purchaseOrder = purchaseOrderService.getPurchaseOrder(id);
				
				String receivedSerialNo="";
				//String assetTag="";
				String assetModelCode="";
				String purchaseRepairStatus ="";
				//String indexSNo="";
				PurchaseOrderRepair purchaseOrderRepair= new PurchaseOrderRepair();
				
				//Vector<HashMap<Integer,String>> vector = new Vector<HashMap<Integer,String>>();
				Vector<String> vector = new Vector<String>();
							
				for(int i=1;i<sheet.getRows();i++){
				
					 AssetModel assetModel = new AssetModel();
					 DeliveryOrderEquipment deliveryOrderEquipment = new DeliveryOrderEquipment();
					 //indexSNo = sheet.getCell(0, i).getContents()!=null?sheet.getCell(0, i).getContents():"";
					 assetModelCode = sheet.getCell(0, i).getContents()!=null?sheet.getCell(0, i).getContents().trim():"";
					 receivedSerialNo = sheet.getCell(1, i).getContents()!=null? sheet.getCell(1, i).getContents().trim():"";
					 //assetTag = sheet.getCell(3, i).getContents()!=null? sheet.getCell(3, i).getContents():"";
					 assetModel.setAssetModelCode(assetModelCode);
					 
					 purchaseOrderRepair = purchaseOrder.findPurchaseOrderRepairs(assetModel,receivedSerialNo);
					 purchaseRepairStatus =  purchaseOrderRepair!=null && purchaseOrderRepair.getRepairStatus()!=null? (String)purchaseOrderRepair.getRepairStatus():"";
					 
					if(purchaseOrderRepair==null){
						deliveryOrderEquipment.setDeleted(true);
						deliveryOrderEquipment.setAssetModel(assetModel);	
					}
					
					else if(purchaseRepairStatus.equalsIgnoreCase(PurchaseOrderRepair.REPAIRSTATUS_RECEIVED)){
						deliveryOrderEquipment.setDeleted(true);
						deliveryOrderEquipment.setAssetModel(purchaseOrderRepair.getAssetModel());
					}
					else
					{
						deliveryOrderEquipment.setAssetModel(purchaseOrderRepair.getAssetModel());
						
					//	AssetEquipmentPK assetEquipmentPK= new AssetEquipmentPK(purchaseOrderRepair.getAssetModel(), receivedSerialNo);
						if(vector.contains(receivedSerialNo))
						{
							deliveryOrderEquipment.setDeleted(true);
						}
						else
						{
							vector.addElement(receivedSerialNo);
						}
						
											
					}
										
					deliveryOrderEquipment.setReceivedSerialNo(receivedSerialNo);
					//deliveryOrderEquipment.setAssetTag(assetTag);
					deliveryOrderEquipments.add(deliveryOrderEquipment);					
				}

				
			}
			
			catch(ArrayIndexOutOfBoundsException e){
						map.put("format","error");
						logger.error(CommonUtil.getStackTrace(e));
				}
				catch(Exception e){
					logger.error(CommonUtil.getStackTrace(e));
				}
				finally{
						if(workbook!=null){
							workbook.close();
						}
				}

		}
		catch(Exception e ){
			logger.error(CommonUtil.getStackTrace(e));
			}
				
			
			map.put("success", "true");
			map.put("result", deliveryOrderEquipments);
			
			
			StringWriter writer = new StringWriter();
	        ObjectMapper mapper = new ObjectMapper();
	        JsonGenerator jsonGenerator;
			try {
				jsonGenerator = mapper.getJsonFactory().createJsonGenerator(writer);
				mapper.writeValue(jsonGenerator, map);
				return writer.toString();
			} catch (IOException e) {
				logger.error(CommonUtil.getStackTrace(e));
			}
			
			return "[]";
			
	}
		
	@RequestMapping(value={"print/{id}"}, method = RequestMethod.GET)
	public void printDeliveryOrder(@PathVariable Integer id,Model model,HttpServletRequest request,HttpServletResponse response) throws IOException {

		try
		{
			ServletOutputStream servletOutputStream = response.getOutputStream();	
			InputStream reportStream = null;
			DeliveryOrder deliveryOrder = deliveryOrderService.getDeliveryOrder(id);
			
			PurchaseOrder purchaseOrder = deliveryOrder.getPurchaseOrder();
			Vendor vendor = purchaseOrder.getVendor();
			Department department = purchaseOrder.getAccessDepartment();
			HashMap details = new HashMap();
			details.put("deliveryOrderCode", deliveryOrder.getDeliveryOrderCode());
			details.put("purchaseOrderCode", purchaseOrder.getPurchaseOrderCode());
			details.put("vendorId", vendor.getVendorId().toString());
			details.put("vendorName", vendor.getVendorName());
			details.put("address", vendor.getContactInfo()!=null? vendor.getContactInfo().getContactAddress():"");
			details.put("contactNo", vendor.getContactInfo()!=null? vendor.getContactInfo().getContactNo():"");
			
			details.put("deliveryOrderDate", deliveryOrder.getDeliveryOrderDateToDisplay());
			details.put("assetType", purchaseOrder.getAssetType());
			details.put("location", purchaseOrder.getLocation().getLocationName());
			details.put("purchaseOrderDate", purchaseOrder.getPurchaseOrderDateToDisplay());
			details.put("purchaseOrderType", purchaseOrder.getPurchaseOrderType());	
			details.put("effectiveStartDate", deliveryOrder.getEffectiveStartDateToDisplay());	
			details.put("effectiveEndDate", deliveryOrder.getEffectiveEndDateToDisplay());	
			details.put("accessDepartment", department!=null? department.getDepartmentName():"-");
			details.put("receivingLocation", deliveryOrder.getLocation().getLocationName());
			details.put("companyCode", purchaseOrder.getCompanyCode());
			
			if(deliveryOrder.isNewDeliveryOrder() && deliveryOrder.isComponentDeliveryOrder()){
				
				
				List<DeliveryOrderComponent> list = deliveryOrder.getDeliveryOrderComponents();	
				reportStream =getClass().getClassLoader().getResourceAsStream("report/DeliveryOrderComp.jasper");	
				JasperRunManager.runReportToPdfStream(reportStream,
						servletOutputStream,
						details,
						new JRBeanCollectionDataSource(list));
				
				
			}
			
			else if(deliveryOrder.isNewDeliveryOrder() && deliveryOrder.isEquipmentDeliveryOrder()){
				
			
				List<DeliveryOrderEquipment> list = deliveryOrder.getDeliveryOrderEquipments();
				 reportStream =getClass().getClassLoader().getResourceAsStream("report/DeliveryOrderEquipNew.jasper");	
				 JasperRunManager.runReportToPdfStream(reportStream,
						 servletOutputStream,
							details,
							new JRBeanCollectionDataSource(list));
					
					
			}
			
			else if(deliveryOrder.isRepairDeliveryOrder()){
				List<DeliveryOrderEquipment> list = deliveryOrder.getDeliveryOrderEquipments();
				reportStream =getClass().getClassLoader().getResourceAsStream("report/DeliveryOrderEquipRepair.jasper");	
				 JasperRunManager.runReportToPdfStream(reportStream,
						 servletOutputStream,
							details,
							new JRBeanCollectionDataSource(list));
					
					
			}
			
			response.setContentType("application/pdf");
			servletOutputStream.flush();
			servletOutputStream.close();
		}
		catch (JRException e)
		{
			// display stack trace in the browser
			logger.error(CommonUtil.getStackTrace(e));
			StringWriter stringWriter = new StringWriter();
			PrintWriter printWriter = new PrintWriter(stringWriter);
			e.printStackTrace(printWriter);
			response.setContentType("text/plain");
			response.getOutputStream().print(stringWriter.toString());
		}

	}
	
	
	
	public boolean checkNullEmpty(Object obj){
		
		boolean flag=true;
		if(obj!=null && !obj.equals("")){
			flag = false;
		}
		return flag;
	}
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(GlobalConstant.DATE_FORMAT_JAVA);
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	
	private void populateModel(Model model,HttpServletRequest request) {
		
		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.addSearchCriteria("purchaseOrderStatus", new InQueryHelper("purchaseOrderStatus",
				Arrays.asList(PurchaseOrder.PURCHASEORDERSTATUS_INPROCESS,PurchaseOrder.PURCHASEORDERSTATUS_NEW)));
		Department accessDepartment = getCurrentDepartment(request);
		if(accessDepartment !=null)
			searchCriteria.addSearchCriteria("accessDepartmentId", accessDepartment.getDepartmentId());
		
		List<PurchaseOrder> purchaseOrders = purchaseOrderService.findPurchaseOrders(searchCriteria);
		model.addAttribute("purchaseOrderList",purchaseOrders);
		
		
		HashMap statusMap = new HashMap();
		statusMap.put(AssetModel.ASSETSTATUS_ACTIVE, "Active");
		statusMap.put(AssetModel.ASSETSTATUS_FAULT, "Fault");
		model.addAttribute("statusMap", statusMap);
		
		
}
	
	private boolean validateDeliveryOrder(DeliveryOrder deliveryOrder,BindingResult result)
	{	
		if(deliveryOrder.getPurchaseOrder().getPurchaseOrderId()==null){
			deliveryOrder.setPurchaseOrder(null);
		}
		
		validator.validate(deliveryOrder, result);
		if(!result.hasErrors())
		{
			
			int compare = deliveryOrder.getPurchaseOrder().getPurchaseOrderDate().compareTo(deliveryOrder.getDeliveryOrderDate());
			if (compare > 0){
				result.rejectValue("deliveryOrderDate", "error.order.checkDODate");
			}			
			else if(deliveryOrder.isNewDeliveryOrder() && deliveryOrder.isEquipmentDeliveryOrder()){
				
				if(checkNullEmpty(deliveryOrder.getEffectiveStartDate()) && !checkNullEmpty(deliveryOrder.getEffectiveEndDate())){
					result.rejectValue("effectiveStartDate", "error.empty");
				}
				else if(!checkNullEmpty(deliveryOrder.getEffectiveStartDate()) && checkNullEmpty(deliveryOrder.getEffectiveEndDate())){
					result.rejectValue("effectiveEndDate", "error.empty");
					
				}
				else if(!checkNullEmpty(deliveryOrder.getEffectiveStartDate()) && !checkNullEmpty(deliveryOrder.getEffectiveEndDate())){
					int res = deliveryOrder.getEffectiveStartDate().compareTo(deliveryOrder.getEffectiveEndDate());
					if ((res > 0 || res == 0)){
						result.rejectValue("effectiveEndDate", "error.order.checkEndDate");
					}
				}
			}
			
		}
		return result.hasErrors();
	}
	
	private void prepareAuditObject(DeliveryOrder deliveryOrder, HttpServletRequest request){
		/* audit start */
		Location loc = findLocation(request, deliveryOrder.getLocation().getLocationId());
		deliveryOrder.setLocation(loc);
		Vendor ven = findVendor(request, deliveryOrder.getPurchaseOrder().getVendor().getVendorId());
		deliveryOrder.getPurchaseOrder().setVendor(ven);
		
		
		if(deliveryOrder.isComponentDeliveryOrder()){
			List<DeliveryOrderComponent> list = deliveryOrder.getDeliveryOrderComponents();
			if(CollectionUtils.isNotEmpty(list)){

				for(DeliveryOrderComponent detail : list){
					if(detail.getAssetModel() != null){
						Integer assetModelId = detail.getAssetModel().getAssetModelId();
						AssetModel tmp  = findAssetModel(request, assetModelId);
						detail.setAssetModel(tmp);
					}
				}
			}
		}
		else if(deliveryOrder.isEquipmentDeliveryOrder()){
			List<DeliveryOrderEquipment> list = deliveryOrder.getDeliveryOrderEquipments();
			if(CollectionUtils.isNotEmpty(list)){

				for(DeliveryOrderEquipment detail : list){
					if(detail.getAssetModel() != null){
						Integer assetModelId = detail.getAssetModel().getAssetModelId();
						AssetModel tmp  = findAssetModel(request, assetModelId);
						detail.setAssetModel(tmp);
					}
				}
			}
		}
			
		
	
		/* audit end */	
	}
	
}
